<?php
namespace app\admin\controller;

class Product extends Base{

    protected $model;
    protected $productDescModel;
    protected $categoryModel;
    public function __construct(){
        parent::__construct();
        $this->model = model('Product');
        $this->productDescModel = model('ProductDesc');
        $this->categoryModel = model('Category');
    }

    public function lst(){
        //$where['status'] = 1;
        $where = array();
        $order = ['id'=>'desc'];
        $data = $this->model->queryData($where,$order);
        $this->assign("data", $data);

        return $this->fetch();
    }

    public function add(){
        if(request()->isPost()){
            $data = request()->param();
            if (!empty($data['thumbs'])) {
                $data['thumbs'] = json_encode($data['thumbs']);
            }
            if(!empty($data['desc'])){
                $data['desc'] = htmlspecialchars_decode($data['desc']);
            }
            if($this->model->saveData($data,false)){
                $data['pid'] = $this->model->id;//商品id
                if($this->productDescModel->saveData($data,false)){
                    return json($this->success('保存成功！'));
                }else{
                    return json($this->error('保存失败！'));
                }
            }else{
                return json($this->error('保存失败！'));
            }



        }
        $categoryData = $this->categoryModel->getTree();
        $this->assign('categoryData', $categoryData);
        // 取出所有的商品分类制作下拉框
        //$typeData = $this->typeModel->select();
        //$this->assign('typeData', $typeData);
        return $this->fetch();
    }
    public function edit(){
        $id = input('id');
        if(request()->isPost()){
            $data = request()->param();
            if($this->model->saveData($data,true)){
                return json($this->success('保存成功！'));
            }else{
                return json($this->error('保存失败！'));
            }
        }

        $data = $this->model->queryDataByID($id);
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function ajaxUpdateStatus(){
        $product_id = input('id');
        $product = $this->model->find($product_id);
        if($product['status'] == 1) {
            $this->model->where(array('id'=>array('eq', $product_id)))->setField('status', 0);
            echo 0;
        } else {
            $this->model->where(array('id'=>array('eq', $product_id)))->setField('status', 1);
            echo 1;
        }
    }
}

